﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using System.Web.Security;
using DevExpress.Web.Mvc;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class UserController :AdminBaseController
    {
        /// <summary>
        /// 用户管理
        /// </summary>
        /// <param name="focusNodeName">选中的节点</param>
        /// <returns>用户管理主页面</returns>
        [AuthorityActionFilter("m_PrvUser", Order = 1)]
        [LogPageActionFilter("用户管理", Order = 2)]
        public ActionResult Index(string focusNodeName = "")
        {
            ViewData["focusNodeName"] = focusNodeName;
            BLL.PrvUser userBLL = new BLL.PrvUser();
            string where = " FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            List<Model.PrvUser> prvUserList = userBLL.GetModelList(where);
            ViewData["isHaveTreeData"] = prvUserList.Count == 0 ? false : true;
            return View();
        }


        /// <summary>
        /// 左边用户组树
        /// </summary>
        /// <param name="focusNodeName">选中的节点</param>
        /// <returns>返回用户树视图</returns>
        public ActionResult UserTree(string focusNodeName = "")
        {
            BLL.PrvUser userBLL = new BLL.PrvUser();
            //string where = " FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            //List<Model.PrvUser> prvUserList = userBLL.GetModelList(where);
            ElingOA6_Admin_DSJCJ.Models.TreeModelList treeModelList = new TreeModelList();
            //if (prvUserList.Count > 0)
 
            //{
            //    foreach (Model.PrvUser grpModel in prvUserList)
            //    {
            //        TreeItemModel treeParentItemModel = new TreeItemModel(null)
            //        {
            //            Id = DevExpressHelper.GetUrl(new { Controller = "User", Action = "EditUser" }) + "|" + grpModel.FLogID,
            //            Name = grpModel.FUserName,
            //            ImageUrl = "/Content/ControlImages/user_Manager.png"
            //        };
            //        treeModelList.Add(treeParentItemModel);
            //    }
            //}

            List<Model.PrvUser> prvUserList = userBLL.GetListDept(GlobalConstant.ENTITYNO);

            BLL.HRDept deptBll = new BLL.HRDept();
            List<Model.HRDept> deptList = deptBll.GetListNoNameByEntityNo(GlobalConstant.ENTITYNO);
           
            foreach (Model.PrvUser prvModel in prvUserList.Where(c => c.FDeptNo == string.Empty))
            {
                TreeItemModel treeParentItemModel = new TreeItemModel(null)
                {
                    Id = DevExpressHelper.GetUrl(new { Controller = "User", Action = "EditUser" }) + "|" + prvModel.FLogID,
                    Name = prvModel.FUserName,
                    ImageUrl = Url.Content("~/Content/ControlImages/user_male.png")
                };
                treeModelList.Add(treeParentItemModel);
            }


            foreach (Model.HRDept deptObj in deptList.Where(c => c.FParentDeptNo == null))
            {
                TreeItemModel treeParentItemModel = new TreeItemModel(null)
                {
                    Id = "dept_" + deptObj.FDeptNo,
                    Name = deptObj.FDeptName,
                    ImageUrl = Url.Content("~/Content/ControlImages/dept_Groups.png")
                };

                SetUser(deptObj.FDeptNo, prvUserList, treeParentItemModel);

                SetChildDept(deptObj.FDeptNo, deptList, prvUserList, treeParentItemModel);


                treeModelList.Add(treeParentItemModel);

            }



            ViewData["focusNodeName"] = focusNodeName;
            return View(treeModelList);
        }


        /// <summary>
        /// 绑定部门人员
        /// </summary>
        /// <param name="deptNo">部门编号</param>
        /// <param name="userList">用户集合</param>
        /// <param name="treeParentItemModel">父级树节点</param>
        private void SetUser(string deptNo, List<Model.PrvUser> userList, TreeItemModel treeParentItemModel)
        {
            foreach (Model.PrvUser prvModel in userList.Where(c => c.FDeptNo == deptNo))
            {
                TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                {
                    Id = DevExpressHelper.GetUrl(new { Controller = "User", Action = "EditUser" }) + "|" + prvModel.FLogID,
                    Name = prvModel.FUserName,
                    ImageUrl = Url.Content("~/Content/ControlImages/user_male.png")
                };
            }
        }



        /// <summary>
        /// 绑定下级部门
        /// </summary>
        /// <param name="preDeptNo">上级部门编号</param>
        /// <param name="deptList">部门集合</param>
        /// <param name="userList">用户集合</param>
        /// <param name="treeParentItemModel">父级树节点</param>
        private void SetChildDept(string preDeptNo, List<Model.HRDept> deptList, List<Model.PrvUser> userList, TreeItemModel treeParentItemModel)
        {
            foreach (Model.HRDept deptObj in deptList.Where(c => c.FParentDeptNo == preDeptNo))
            {
                TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                {
                    Id = "dept_" + deptObj.FDeptNo,
                    Name = deptObj.FDeptName,
                    ImageUrl = Url.Content("~/Content/ControlImages/dept_Groups.png")
                };

                SetUser(deptObj.FDeptNo, userList, treeChildItemModel);

                SetChildDept(deptObj.FDeptNo, deptList, userList, treeChildItemModel);
            }
        }

        /// <summary>
        /// 修改用户组
        /// </summary>
        /// <param name="userID">用户编号</param>
        /// <returns>返回修改用户视图</returns>
        public ActionResult EditUser(string userID)
        {
            return EditUser(userID, "", "EDIT", null);
        }
        /// <summary>
        /// 增加用户组
        /// </summary>
        /// <returns>返回增加用户视图</returns>
        public ActionResult AddGroup()
        {
            //return AddGroup("", null);
            return EditUser("0", "", "ADD_SAME", new Model.PrvUser());
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="prvUserModel">用户信息</param>
        /// <returns>返回保存后视图</returns>
        public ActionResult Save(Model.PrvUser prvUserModel)
        {
            bool isSuccess = true;
            string errorMessage = "";
            ActionResult actionResult = null;
            //数据逻辑验证
            if (prvUserModel.FLogID.Trim() == "")
            {
                errorMessage = "用户名称不能为空";
                isSuccess = false;
            }
            if (prvUserModel.FUserName.Trim() == "")
            {
                errorMessage = "用户不能为空";
                isSuccess = false;
            }
            prvUserModel.FEntityNo = GlobalConstant.ENTITYNO;
            BLL.PrvUser userBll = new BLL.PrvUser();
            string users = Fetch.Post("hdOrgUserSelect");
            List<string> userGroupList = new List<string>();
            if (users != "")
            {
                userGroupList = users.Split(new char[1] { ',' }).ToList();
            }
            //string funcs = Fetch.Post("hdFunctionSelect");
            //List<string> dirUserList = new List<string>();

            //if (funcs != "")
            //{
            //    dirUserList = funcs.Split(new char[1] { ',' }).ToList();
            //}
            prvUserModel.FIsLookAllDaily = Fetch.Post("FIsLookAllDaily") == "C" ? "Y" : "N";
            prvUserModel.FIsInstruct = CheckBoxExtension.GetValue<bool>("FIsInstruct") == true ? "Y" : "N";
            switch (Fetch.Post("hdMethod"))
            {
                case "ADD_SAME":
                    {
                        if (userBll.Exists(prvUserModel.FLogID, prvUserModel.FEntityNo))
                        {
                            errorMessage = "用户编号已存在";
                            isSuccess = false;
                        }
                        else
                        {
                            try
                            {
                                prvUserModel.Fpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(GlobalConstant.ENTITYNO + prvUserModel.FLogID + "123456", "MD5");
                                userBll.AddPrvUser(prvUserModel, userGroupList);
                                //增加成功
                                ViewData["focusKey"] = DevExpressHelper.GetUrl(new { Controller = "User", Action = "EditUser" }) + "|" + prvUserModel.FLogID;//焦点定位的节点ID
                                ViewData["methodFromType"] = Fetch.Post("hdMethod");
                                ViewData["nodeText"] = prvUserModel.FUserName;
                                actionResult = View("SuccessMessageByTree");
                            }
                            catch
                            {
                                errorMessage = "操作异常:";
                            }


                        }
                        if (actionResult == null)
                        {
                            actionResult = EditUser("0", errorMessage, Fetch.Post("hdMethod"), prvUserModel);
                        }
                        break;
                    }
                case "EDIT":
                    {
                        if (isSuccess)
                        {
                            try
                            {
                                userBll.EditPrvUser(prvUserModel, userGroupList);
                                //修改成功
                                ViewData["RedirectURL"] = Url.Action("EditUser", "User", new { userID = prvUserModel.FLogID });
                                ViewData["methodFromType"] = Fetch.Post("hdMethod");
                                ViewData["nodeText"] = prvUserModel.FUserName;
                                actionResult = View("SuccessMessageByTree");
                            }
                            catch
                            {
                                errorMessage = "操作异常:";
                            }
                        }
                        if (actionResult == null)
                        {
                            actionResult = EditUser(prvUserModel.FLogID, errorMessage, Fetch.Post("hdMethod"), prvUserModel);
                        }
                        break;
                    }
            }

            return actionResult;
        }
        /// <summary>
        ///  删除用户
        /// </summary>
        /// <param name="userIDEn">用户ID</param>
        /// <returns>返回删除是否成功</returns>
        [HttpPost]
        public string DeleteUser(string userIDEn)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string userID = "0";
            if (userIDEn != "")
            {
                try
                {
                    userID = GenerateUtil.Decrypt(userIDEn, "FLogID");
                    try
                    {
                        BLL.PrvUser userBll = new BLL.PrvUser();
                        userBll.Delete(userID, GlobalConstant.ENTITYNO);
                        jsonstr = "SUCCESS";
                    }
                    catch
                    {
                        errorMessage = "操作异常";
                    }
                }
                catch
                {
                    errorMessage = "参数错误";
                }

                if (jsonstr == "FAILED")
                {
                    jsonstr += "FAILED|" + errorMessage;
                }
            }
            return jsonstr;
        }
        /// <summary>
        /// 密码重置
        /// </summary>
        /// <param name="userIDEn">用户编号（加密）</param>
        /// <returns>是否重置成功</returns>
        [HttpPost]
        public string ResetPwd(string userIDEn)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string userID = "0";
            if (userIDEn != "")
            {
                try
                {
                    userID = GenerateUtil.Decrypt(userIDEn, "FLogID");
                    try
                    {
                        BLL.PrvUser userBll = new BLL.PrvUser();
                        string fpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(GlobalConstant.ENTITYNO + userID + "123456", "MD5");
                        userBll.ResetPwd(userID, fpassword, GlobalConstant.ENTITYNO);
                        jsonstr = "SUCCESS";
                    }
                    catch
                    {
                        errorMessage = "操作异常";
                    }
                }
                catch
                {
                    errorMessage = "参数错误";
                }

                if (jsonstr == "FAILED")
                {
                    jsonstr += "FAILED|" + errorMessage;
                }
            }
            return jsonstr;
        }

        #region 私有方法
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="userID">用户编号</param>
        /// <param name="jsAlert">异常内容</param>
        /// <param name="methodType">类型  ADD_SAME 新增; EDIT 修改</param>
        /// <param name="prvUserModel">用户信息</param>
        /// <returns>增加修改后显示视图</returns>
        private ActionResult EditUser(string userID, string jsAlert, string methodType, Model.PrvUser prvUserModel)
        {
            BLL.PrvUser userBll = new BLL.PrvUser();
            BLL.PrvUserGroup prvUserGroupBLL = new BLL.PrvUserGroup();
            BLL.PrvGroup prvGroupBLL = new BLL.PrvGroup();
            //增加和修改同一个页面
            ViewData["hdMethod"] = methodType;//类型  ADD_SAME 新增; EDIT 修改
            if (prvUserModel == null)
            {
                prvUserModel = userBll.GetModel(userID, GlobalConstant.ENTITYNO);
            }
            if (prvUserModel != null)
            {
                //获取所有菜单权限
                BLL.Index adminIndexBLL = new BLL.Index();

                List<Model.PrvFunctList> prvFunctListList = new List<Model.PrvFunctList>();
                if (prvUserModel.FLogID == "admin")
                {
                    prvFunctListList = adminIndexBLL.GetPrvFunctList();
                }
                else
                {
                    prvFunctListList = adminIndexBLL.GetPrvFunctList(prvUserModel.FLogID);
                }
                string treeJsonStr = "";
                if (prvFunctListList.Count > 0)
                {

                    treeJsonStr += "[";
                    List<Model.PrvFunctList> prvFirstList = (from m in prvFunctListList
                                                             where m.FPreFunctNo == "m_PrvFunctList"
                                                             orderby m.Fsort
                                                             select m).ToList();
                    foreach (Model.PrvFunctList prvModel in prvFirstList)
                    {
                        treeJsonStr += "{'title':'" + prvModel.FfunctName + "','key':'" + prvModel.FFunctNo + "','expand':true,'icon':'" + (prvModel.FPictName.Trim() != "" ? Url.Content(prvModel.FPictName):"") + "'";
                        List<Model.PrvFunctList> tmpModelList = (from m in prvFunctListList
                                                                 where m.FPreFunctNo == prvModel.FFunctNo
                                                                 orderby m.Fsort
                                                                 select m).ToList();
                        if (tmpModelList.Count > 0)
                        {
                            treeJsonStr += ",'children':[";

                            GetChildFuncList(tmpModelList, ref treeJsonStr, prvFunctListList);
                            treeJsonStr += "]";
                        }
                        else
                        {
                            treeJsonStr += ",'href':'" + Url.Action("Index", prvModel.FfunctURL) + "','target':'content'";
                        }
                        treeJsonStr += "},";
                    }
                    treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                    treeJsonStr += "]";
                    treeJsonStr = treeJsonStr.Replace("\\", "");
                    treeJsonStr = treeJsonStr.Replace("'", "\"");
                }
                ViewData["treeJsonStrUserFunc"] = treeJsonStr;


                prvUserModel.FLogIDEn = GenerateUtil.Encrypt(prvUserModel.FLogID == null ? "0" : prvUserModel.FLogID.ToString(), "FLogID");
                BLL.HREmpl empBll = new BLL.HREmpl();
                prvUserModel.FEmpName = empBll.GetEmpName(GlobalConstant.ENTITYNO, prvUserModel.FEmplNo);
                string where = " FEntityNo='" + GlobalConstant.ENTITYNO + "'";
                //获取用户组
                List<Model.PrvGroup> prvGroupList = prvGroupBLL.GetModelList(where);//获取所有用户组
                ElingOA6_Admin_DSJCJ.Models.TreeModelList treeUserOrgModelList = new TreeModelList();
                if (prvGroupList.Count > 0)
                {

                    TreeItemModel treeParentItemModel = new TreeItemModel(null)
                    {
                        Id = "",
                        Name = "全选",
                        ImageUrl = Url.Content("~/Content/ControlImages/user_group.png")
                    };
                    foreach (Model.PrvGroup prvModel in prvGroupList)
                    {
                        TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                        {
                            Id = "user" + "|" + prvModel.FGroupNo,
                            Name = prvModel.FGroupName,
                            ImageUrl = Url.Content("~/Content/ControlImages/user_group.png")

                        };
                    }
                    treeUserOrgModelList.Add(treeParentItemModel);
                }
                ViewData["treeModelUserList"] = treeUserOrgModelList;
                //获取目录用户组
                //BLL.DirPrvGroup dirPrvGroupBLL = new BLL.DirPrvGroup();
                //BLL.DirPrvUserGroup dirPrvUserGroupBLL = new BLL.DirPrvUserGroup();
                //where = " FEntityNo='" + GlobalConstant.ENTITYNO + "'";
                //List<Model.DirPrvGroup> dirPrvGroupList = dirPrvGroupBLL.GetModelList(where);//获取所有目录
                //Models.TreeModelList treeUserPrvModelList = new Models.TreeModelList();

                //if (dirPrvGroupList.Count > 0)
                //{
                //    TreeItemModel treeParentItemModel = new TreeItemModel(null)
                //    {
                //        Id = "",
                //        Name = "全选",
                //        ImageUrl = Url.Content("~/Content/ControlImages/groups.png")
                //    };
                //    foreach (Model.DirPrvGroup prvModel in dirPrvGroupList)
                //    {
                //        TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                //        {
                //            Id = "child" + "|" + prvModel.FGroupNo,
                //            Name = prvModel.FGroupName,
                //            ImageUrl = Url.Content("~/Content/ControlImages/groups.png")
                //        };
                //    }
                //    treeUserPrvModelList.Add(treeParentItemModel);
                //}
                //ViewData["treeModelFunctionList"] = treeUserPrvModelList;
                //隐藏字段

                ViewData["jsAlert"] = jsAlert;
                ViewData["userID"] = userID;
                where = " FLogID='" + prvUserModel.FLogID + "' and  FEntityNo='" + GlobalConstant.ENTITYNO + "'";
                List<string> groupNoList = prvUserGroupBLL.GetGroupNoList(where); //当前用户所有用户组ID
                //List<string> dirPrvUserGroupNoList = dirPrvUserGroupBLL.GetDirGroupNoList(where);//当前用户所有目录用户组ID
                string groupNos = "";
                if (groupNoList.Count > 0)
                {
                    foreach (string s in groupNoList)
                    {
                        groupNos += s + ",";
                    }
                    groupNos = groupNos.Substring(0, groupNos.LastIndexOf(","));
                }
                //string dirGroupNos = "";
                //if (dirPrvUserGroupNoList.Count > 0)
                //{
                //    foreach (string s in dirPrvUserGroupNoList)
                //    {
                //        dirGroupNos += s + ",";
                //    }
                //    dirGroupNos = dirGroupNos.Substring(0, dirGroupNos.LastIndexOf(","));
                //}

                ViewData["groupNos"] = groupNos;
                //ViewData["dirGroupNos"] = dirGroupNos;
                return View("EditUser", prvUserModel);
            }
            return null;
        }

        /// <summary>
        /// 递归获取组织用户树形菜单
        /// </summary>
        /// <param name="orgChildList">用户列表</param>
        /// <param name="treeParentItemModel">父级树节点</param>
        /// <param name="prvGroupList">用户组列表</param>
        private void GetChildOrgList(List<Model.PrvUser> orgChildList, TreeItemModel treeParentItemModel, List<Model.PrvUser> prvGroupList)
        {
            foreach (Model.PrvUser orgModel in orgChildList)
            {
                TreeItemModel treeChildItemModel = new TreeItemModel(treeParentItemModel)
                {
                    Id = "" + "|" + orgModel.FLogID,
                    Name = orgModel.FUserName
                };


                //List<Model.PrvUser> tmpModelList = (from m in prvGroupList
                //                                     where m.FParentDeptNo == orgModel.FDeptNo
                //                                     select m).ToList();


                //获取人员
                //BLL.PrvUser userBLL = new BLL.PrvUser();
                //string where = " FEntityNo='" + GlobalConstant.ENTITYNO + "' and FDeptNo='" + orgModel.FLogID + "' ";
                //List<Model.PrvUser> prvUserList = userBLL.GetModelList(where);
                //if (tmpModelList.Count > 0 || prvUserList.Count > 0)
                //{
                //    foreach (Model.PrvUser userModel in prvUserList)
                //    {

                //        TreeItemModel treeChildUserItemModel = new TreeItemModel(treeChildItemModel)
                //        {
                //            Id = "user" + "|" + userModel.FLogID,
                //            Name = userModel.FUserName
                //        };
                //        if (tmpModelList.Count > 0)
                //        {
                //            GetChildOrgList(tmpModelList, treeChildUserItemModel, prvGroupList);
                //        }
                //    }
                //}
            }
        }

        /// <summary>
        /// 递归获取权限树形菜单
        /// </summary>
        /// <param name="prvChildList"></param>
        /// <param name="treeJsonStr"></param>
        private void GetChildFuncList(List<Model.PrvFunctList> prvChildList, ref string treeJsonStr, List<Model.PrvFunctList> prvFunctListList)
        {
            foreach (Model.PrvFunctList prvModel in prvChildList)
            {
                treeJsonStr += "{'title':'" + prvModel.FfunctName + "','key':'" + prvModel.FFunctNo + "','expand':true,'icon':'" + (prvModel.FPictName.Trim() != "" ? Url.Content(prvModel.FPictName):"" )+ "'";
                List<Model.PrvFunctList> tmpModelList = (from m in prvFunctListList
                                                         where m.FPreFunctNo == prvModel.FFunctNo
                                                         orderby m.Fsort
                                                         select m).ToList();
                if (tmpModelList.Count > 0)
                {
                    treeJsonStr += ",'children':[";
                    GetChildFuncList(tmpModelList, ref treeJsonStr, prvFunctListList);
                    treeJsonStr += "]";
                }
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
        }
        #endregion
    }
}
